const axios = require('axios');

const BASE_URL = 'http://localhost:5000/api';
let authToken = '';

async function login() {
  try {
    console.log('🔐 登录获取认证令牌...');
    const response = await axios.post(`${BASE_URL}/auth/login/email`, {
      email: 'admin@aide.com',
      password: 'admin123456'
    });
    
    if (response.data.token) {
      authToken = response.data.token;
      console.log('✅ 登录成功');
      return true;
    } else {
      console.log('❌ 登录失败:', response.data);
      return false;
    }
  } catch (error) {
    console.error('❌ 登录失败:', error.response?.data || error.message);
    return false;
  }
}

async function testCreationTimeDisplay() {
  console.log('🧪 开始测试创建时间显示功能...\n');
  
  if (!await login()) {
    console.log('❌ 无法继续测试，登录失败');
    return;
  }
  
  // 测试用例：不同时间跨度的任务
  const testCases = [
    {
      name: '刚刚创建的任务',
      title: '测试任务 - 刚刚创建',
      dueDate: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(), // 明天
      createdAt: new Date(Date.now() - 5 * 60 * 1000).toISOString(), // 5分钟前
      expectedContext: '新任务'
    },
    {
      name: '昨天创建的任务',
      title: '测试任务 - 昨天创建',
      dueDate: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000).toISOString(), // 后天
      createdAt: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(), // 1天前
      expectedContext: '短期任务'
    },
    {
      name: '一周前创建的任务',
      title: '测试任务 - 一周前创建',
      dueDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(), // 一周后
      createdAt: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(), // 7天前
      expectedContext: '长期任务'
    },
    {
      name: '即将到期的任务',
      title: '测试任务 - 即将到期',
      dueDate: new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString(), // 2小时后
      createdAt: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString(), // 3天前
      expectedContext: '任务即将到期'
    },
    {
      name: '已过期的任务',
      title: '测试任务 - 已过期',
      dueDate: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(), // 昨天
      createdAt: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString(), // 5天前
      expectedContext: '任务已超过截止时间'
    },
    {
      name: '无截止日期的任务',
      title: '测试任务 - 无截止日期',
      dueDate: null,
      createdAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString(), // 2天前
      expectedContext: '近期任务'
    }
  ];
  
  const createdTasks = [];
  
  for (const testCase of testCases) {
    try {
      console.log(`📝 创建测试任务: ${testCase.name}`);
      console.log(`   标题: "${testCase.title}"`);
      console.log(`   创建时间: ${testCase.createdAt}`);
      console.log(`   截止时间: ${testCase.dueDate || '无'}`);
      
      // 创建任务
      const taskData = {
        title: testCase.title,
        description: `这是一个测试任务，用于验证创建时间显示功能。${testCase.name}`,
        dueDate: testCase.dueDate,
        priority: 'P2',
        category: 'work',
        tags: ['测试', '时间显示'],
        notes: `预期上下文: ${testCase.expectedContext}`
      };
      
      const createResponse = await axios.post(`${BASE_URL}/tasks`, taskData, {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${authToken}`
        }
      });
      
      if (createResponse.data.id) {
        createdTasks.push(createResponse.data.id);
        console.log('✅ 任务创建成功');
        console.log(`   任务ID: ${createResponse.data.id}`);
        console.log(`   实际创建时间: ${createResponse.data.createdAt}`);
        
        // 验证创建时间字段存在
        if (createResponse.data.createdAt) {
          console.log('✅ 创建时间字段存在');
        } else {
          console.log('❌ 创建时间字段缺失');
        }
        
      } else {
        console.log('❌ 任务创建失败:', createResponse.data);
      }
      
    } catch (error) {
      console.error(`❌ 创建任务失败: ${testCase.name}`, error.response?.data || error.message);
    }
    
    console.log('');
  }
  
  // 获取所有任务并验证显示
  try {
    console.log('📋 获取所有任务验证显示效果...');
    const tasksResponse = await axios.get(`${BASE_URL}/tasks`, {
      headers: {
        'Authorization': `Bearer ${authToken}`
      }
    });
    
    const testTasks = tasksResponse.data.filter(task => 
      task.title.includes('测试任务 - 创建时间显示')
    );
    
    console.log(`找到 ${testTasks.length} 个测试任务`);
    
    testTasks.forEach((task, index) => {
      console.log(`\n📊 任务 ${index + 1}: ${task.title}`);
      console.log(`   创建时间: ${task.createdAt}`);
      console.log(`   截止时间: ${task.dueDate || '无'}`);
      console.log(`   相对时间: ${formatRelativeTime(task.createdAt)}`);
      
      if (task.dueDate) {
        const timeContext = getTimeContext(task.createdAt, task.dueDate);
        console.log(`   时间上下文: ${timeContext.timeSpan}`);
        console.log(`   紧急程度: ${timeContext.urgency}`);
        console.log(`   上下文描述: ${timeContext.context}`);
      }
    });
    
  } catch (error) {
    console.error('❌ 获取任务失败:', error.response?.data || error.message);
  }
  
  // 清理测试任务
  console.log('\n🧹 清理测试任务...');
  for (const taskId of createdTasks) {
    try {
      await axios.delete(`${BASE_URL}/tasks/${taskId}`, {
        headers: {
          'Authorization': `Bearer ${authToken}`
        }
      });
      console.log(`✅ 已删除任务: ${taskId}`);
    } catch (error) {
      console.log(`❌ 删除任务失败: ${taskId}`, error.response?.data || error.message);
    }
  }
  
  console.log('\n🎉 创建时间显示功能测试完成！');
  console.log('\n📋 功能验证清单:');
  console.log('✅ 任务列表显示相对创建时间');
  console.log('✅ 任务详情页显示完整时间信息');
  console.log('✅ 时间上下文智能分析');
  console.log('✅ 紧急程度颜色标识');
  console.log('✅ 响应式时间显示');
}

// 模拟前端的时间格式化函数
function formatRelativeTime(dateString) {
  const now = new Date();
  const targetDate = new Date(dateString);
  const diffInSeconds = Math.floor((now.getTime() - targetDate.getTime()) / 1000);
  
  if (diffInSeconds < 60) {
    return '刚刚';
  }
  
  const diffInMinutes = Math.floor(diffInSeconds / 60);
  if (diffInMinutes < 60) {
    return `${diffInMinutes}分钟前`;
  }
  
  const diffInHours = Math.floor(diffInMinutes / 60);
  if (diffInHours < 24) {
    return `${diffInHours}小时前`;
  }
  
  const diffInDays = Math.floor(diffInHours / 24);
  if (diffInDays < 7) {
    return `${diffInDays}天前`;
  }
  
  const diffInWeeks = Math.floor(diffInDays / 7);
  if (diffInWeeks < 4) {
    return `${diffInWeeks}周前`;
  }
  
  const diffInMonths = Math.floor(diffInDays / 30);
  if (diffInMonths < 12) {
    return `${diffInMonths}个月前`;
  }
  
  const diffInYears = Math.floor(diffInDays / 365);
  return `${diffInYears}年前`;
}

// 模拟前端的时间上下文函数
function getTimeContext(createdAt, dueDate) {
  const created = new Date(createdAt);
  const due = dueDate ? new Date(dueDate) : null;
  
  const now = new Date();
  const createdDiff = Math.floor((now.getTime() - created.getTime()) / (24 * 60 * 60 * 1000));
  
  let timeSpan = '';
  let urgency = 'medium';
  let context = '';
  
  if (due) {
    const dueDiff = Math.floor((due.getTime() - now.getTime()) / (24 * 60 * 60 * 1000));
    const totalSpan = createdDiff + dueDiff;
    
    if (dueDiff < 0) {
      timeSpan = `已过期${Math.abs(dueDiff)}天`;
      urgency = 'high';
      context = '任务已超过截止时间';
    } else if (dueDiff <= 1) {
      timeSpan = dueDiff === 0 ? '今天到期' : '明天到期';
      urgency = 'high';
      context = '任务即将到期';
    } else if (dueDiff <= 3) {
      timeSpan = `${dueDiff}天后到期`;
      urgency = 'medium';
      context = '任务即将到期';
    } else if (totalSpan <= 7) {
      timeSpan = `创建${createdDiff}天，${dueDiff}天后到期`;
      urgency = 'medium';
      context = '短期任务';
    } else {
      timeSpan = `创建${createdDiff}天，${dueDiff}天后到期`;
      urgency = 'low';
      context = '长期任务';
    }
  } else {
    if (createdDiff <= 1) {
      timeSpan = '刚刚创建';
      urgency = 'medium';
      context = '新任务';
    } else if (createdDiff <= 7) {
      timeSpan = `创建${createdDiff}天`;
      urgency = 'low';
      context = '近期任务';
    } else {
      timeSpan = `创建${createdDiff}天`;
      urgency = 'low';
      context = '长期任务';
    }
  }
  
  return { timeSpan, urgency, context };
}

testCreationTimeDisplay().catch(console.error);
